package com.mengxuegu.oauth2.server.service;


import com.mengxuegu.oauth2.web.entities.SysPermission;
import com.mengxuegu.oauth2.web.entities.SysRole;
import com.mengxuegu.oauth2.web.entities.SysUser;
import com.mengxuegu.oauth2.web.mapper.SysRoleMapper;
import com.mengxuegu.oauth2.web.service.SysPermissionService;
import org.assertj.core.util.Lists;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;
import java.util.List;


public abstract class AbstractUserDetailsService implements UserDetailsService {
    @Resource
    private SysPermissionService sysPermissionService;
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = findSysUser(username);
        List<String> permissionCodes = findSysPermission(sysUser);
        List<String> roleCodes = findSysRole(sysUser);
        roleCodes.addAll(permissionCodes);
        setAuthorities(sysUser, roleCodes);
        return sysUser;
    }

    abstract SysUser findSysUser(String usernameOrMobile);


    public List<String> findSysPermission(SysUser sysUser) throws UsernameNotFoundException {
        if (sysUser == null) {
            throw new UsernameNotFoundException("未查询到有效用户信息");
        }
        List<SysPermission> sysPermissions = sysPermissionService.findByUserId(sysUser.getId());
        sysUser.setPermissions(sysPermissions);

        List<String> codeList = Lists.newArrayList();
        sysPermissions.forEach(permission -> codeList.add(permission.getCode()));
        return codeList;
    }

    public List<String> findSysRole(SysUser sysUser) {
        if (sysUser == null) {
            throw new UsernameNotFoundException("未查询到有效用户信息");
        }
        List<SysRole> sysRoles = sysRoleMapper.findByUserId(sysUser.getId());
        sysUser.setRoleList(sysRoles);
        List<String> roleCodeList = Lists.newArrayList();
        sysRoles.forEach(role -> roleCodeList.add(role.getRoleCode()));
        return roleCodeList;
    }

    public void setAuthorities(SysUser sysUser, List<String> roleCodeList) {
        List<GrantedAuthority> authorities = Lists.newArrayList();
        roleCodeList.forEach(roleCode -> authorities.add(new SimpleGrantedAuthority(roleCode)));
        sysUser.setAuthorities(authorities);
    }
}
